package ferp.center.server.servlet.profile;

import ferp.center.network.request.RequestProfileCreate;
import ferp.center.network.response.ResponseProfileCreate;
import ferp.center.server.Action;
import ferp.center.server.entity.Device;
import ferp.center.server.entity.Profile;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * User: igorgok
 * Date: 5/10/12 1:14 PM
 */
public class ProfileCreate extends HttpServlet
{
  protected void doPost(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, response, RequestProfileCreate.class, new Action.Write<RequestProfileCreate, ResponseProfileCreate>()
    {
      @Override
      public ResponseProfileCreate run(EntityManager em, RequestProfileCreate input) throws IOException
      {
        Profile p = null;
        Date now = new Date();

        if (input.id != 0)
          p = em.find(Profile.class, input.id);

        final boolean create = (p == null);

        if (create)
          p = new Profile();

        // update profile fields if needed
        if (p.getDevice(em) == null)
          p.setDevice(getDevice(em, input, request));
        if (p.getName() == null || !p.getName().equals(input.name))
          p.setName(input.name);
        if (p.getLocale() == null || !p.getLocale().equals(input.locale))
          p.setLocale(input.locale);
        //p.setPoolBalance(input.poolBalance);
        if (p.getLastPlayedPoolSize() != input.lastPlayedPoolSize)
          p.setLastPlayedPoolSize(input.lastPlayedPoolSize);

        // update access time
        p.setAccessed(now);

        if (create)
        {
          p.setCreated(now);

          em.persist(p);
          em.flush();
        }

        ResponseProfileCreate result = new ResponseProfileCreate();

        result.id = p.getKey().getId();

        return result;
      }
    });
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
  }

  @SuppressWarnings("unchecked")
  private Device getDevice(EntityManager em, RequestProfileCreate rpc, HttpServletRequest request)
  {
    Device.Location location = new Device.Location(request);
    Query q = em.createQuery("SELECT d FROM Device d WHERE d.id = ?1");

    q.setParameter(1, rpc.phone);
    q.setMaxResults(1);
    List<Device> devices = q.getResultList();

    if (devices.size() > 0)
    {
      Device d = devices.get(0);

      if (!d.getCountry().equalsIgnoreCase(location.country))
        d.setCountry(location.country);
      if (!d.getRegion().equalsIgnoreCase(location.region))
        d.setRegion(location.region);
      if (!d.getCity().equalsIgnoreCase(location.city))
        d.setCity(location.city);

      return d;
    }

    Device d = new Device();

    d.setID(rpc.phone);
    d.setCreated(new Date());
    d.setCountry(location.country);
    d.setRegion(location.region);
    d.setCity(location.city);

    em.persist(d);
    em.flush();

    return d;
  }
}
